package com.feihong.txgw.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.message.LocationMessage;
import com.feihong.txgw.model.bean.location.LocationInfo;
import com.feihong.txgw.model.bean.user.CityInfo;
import com.feihong.txgw.utils.LocationCallBack;
import com.feihong.txgw.utils.LocationTools;
import com.feihong.txgw.utils.PreferenceTools;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.manage.ThreadPoolManager;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.atomic.AtomicBoolean;

import cn.pedant.SweetAlert.SweetAlertDialog;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW.
 * 飞宏电子
 */

@RuntimePermissions
public class WelcomeActivity extends Activity {


    private AtomicBoolean isShowDilog;
    private static final String TAG = "通讯100";
    private LocationTools locationTools;

//    private ShorCut shorCutUtil;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        setContentView(R.layout.activity_welcome);
        isShowDilog = new AtomicBoolean(false);

        WelcomeActivityPermissionsDispatcher.findLocationWithCheck(this);
        ThreadPoolManager.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                RefreshToken.getInstance().RetrofitRefreshTokenForPost();
            }
        });

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
//            shorCutUtil = new ShorCut(this);
//            shorCutUtil.initShortCus();
//        }
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
                Intent intent = new Intent();
                intent.setClass(WelcomeActivity.this, HomeActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                finish();
        }
    };
    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE})
    void findLocation() {
        findLocation(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        WelcomeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE})
    void showRationaleForContact(PermissionRequest request) {
        request.proceed();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE})
    void onDeniedWelPermission() {
        if (isShowDilog.compareAndSet(false, true)) {
            final SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
            dialog.setTitleText("权限不足");
            dialog.setContentText("您没有开启此应用的使用电话或位置权限。为了能够正常的使用此应用，请您开启电话和位置权限。 \n                             ");
            dialog.setCancelable(false);
            dialog.setNeutralText("知道了");
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    finish();
                    overridePendingTransition(R.anim.fade_in_from_left, R.anim.slide_in_left);
                }
            });
            dialog.show();
        }
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE})
    void onNaverWelPermission() {
        if (isShowDilog.compareAndSet(false, true)) {
            final SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE);
            dialog.setTitleText("权限不足");
            dialog.setContentText("您没有开启此应用的使用电话或位置权限。为了能够正常的使用此应用，请您开启电话和位置权限。 \n                             ");
            dialog.setCancelable(false);
            dialog.setNeutralText("知道了");
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    finish();
                    overridePendingTransition(R.anim.fade_in_from_left, R.anim.slide_in_left);
                }
            });
            dialog.show();
        }
    }

    //定位
    public void findLocation(Activity context) {
        locationTools = new LocationTools(context, new LocationCallBack() {
            @Override
            public void successGetLocation(LocationInfo info) {
                if (info != null) {
                    LogUtils.i("定位", info.toString());
                    CityInfo cityInfo = new CityInfo();
                    cityInfo.setCityCode(info.getCityCode());
                    cityInfo.setCityName(info.getCity());
                    cityInfo.setLatitude(info.getLatitude() + "");
                    cityInfo.setLongitude(info.getLongitude() + "");

                    if (!TextUtils.isEmpty(info.getCity().toString())) {

                    }
                    if (UserLoginInfo.setUserCityInfo(cityInfo)) {
                        Log.i(TAG, "successGetLocation: 设置成功");
                        EventBus.getDefault().post(new LocationMessage());
                    } else {
                        Log.i(TAG, "successGetLocation: 设置失败");
                        Toast.makeText(WelcomeActivity.this, "设置定位信息失败!", Toast.LENGTH_SHORT).show();
                    }
                    mHandler.sendEmptyMessageDelayed(1,0);
                } else {
                    LogUtils.i("通讯顾问", "定位" + UserLoginInfo.getUserCityInfo().toString());
                    //设置默认城市   乌鲁木齐
                    Toast.makeText(WelcomeActivity.this, "定位失败,请手动选择城市!", Toast.LENGTH_SHORT).show();
                    mHandler.sendEmptyMessageDelayed(1,0);
                }
            }

            @Override
            public void error(String error) {

                LogUtils.i("通讯顾问", "定位" + UserLoginInfo.getUserCityInfo().toString());
                switch (error) {
                    case "4":
                    case "5":
                        Toast.makeText(WelcomeActivity.this, "定位失败,请检查网络", Toast.LENGTH_SHORT).show();
                        break;
                    case "12":
                        Toast.makeText(WelcomeActivity.this, "请在设备的设置中开启app的定位权限", Toast.LENGTH_SHORT).show();
                        break;
                    case "13":
                        Toast.makeText(WelcomeActivity.this, "定位失败,请检查网络、GPS是否开启以及定位权限是否开启", Toast.LENGTH_SHORT).show();
                        break;
                    case "14":
                        Toast.makeText(WelcomeActivity.this, "定位失败,请到相对开阔的露天场所再次尝试", Toast.LENGTH_SHORT).show();
                        break;
                    case "18":
                        Toast.makeText(WelcomeActivity.this, "定位失败,建议手机关闭飞行模式，并打开WIFI开关", Toast.LENGTH_SHORT).show();
                        break;
                    case "19":
                        Toast.makeText(WelcomeActivity.this, "定位失败,建议手机插上sim卡，打开WIFI开关", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(WelcomeActivity.this, "定位失败,请手动选择城市", Toast.LENGTH_SHORT).show();
                        break;
                }
                mHandler.sendEmptyMessageDelayed(1,0);
            }
        });
        locationTools.startLocation();
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationTools != null) {
            locationTools.stopLocation();
        }
    }
}
